package com.example.controllers;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.beans.User;
import com.example.dao.UserRepository;
import com.example.dto.Result;
import com.example.dto.ResultUtil;
import com.example.service.RegisterImpl;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootConfiguration
@EnableSwagger2
@RestController
public class MainController {
	
	private final static Logger log= LoggerFactory.getLogger(MainController.class);
	
	@Autowired
	private RegisterImpl registerImpl;
	
	@Autowired
	private UserRepository userRepository;
	
	/**
	 * 用戶注冊
	 * @param user 用戶json對象
	 * @param bindingResult  用戶參數校驗結果
	 * @return 用戶列表
	 */
    @PostMapping(value="/register")
    @ApiOperation(value="用戶注冊",notes="使用姓名和年齡來注冊用戶")
    @ApiImplicitParams({
    	@ApiImplicitParam(name="user",value="用戶json對象",required=true,dataType="User")
    })
    public void register(@Valid User user,BindingResult bindingResult){
    	
    	
    	if(bindingResult.hasErrors()) throw new RuntimeException(bindingResult.getFieldError().getDefaultMessage());
    	

    		
    }
    
    /**
     * 返回所有用戶列表
     * @return 所有用戶列表
     */
    @GetMapping(value="/getUsers")
    public Result getUsers(){
    	
    	return ResultUtil.success(registerImpl.getUserList());
    }
    
    @PostMapping(value="/testThrow")
    @ApiOperation(value="異常測試",notes="測試捕獲控制層的異常並處理全局異常")
    public void testThrow(){
    	
    	  throw new RuntimeException("ctrl异常");
    	  
    }
    
    /**
     * 
     * @param id
     * @return
     */
    @GetMapping(value="/getUserById/{id}")
    public Result getUserById(@PathVariable("id") int id){
    		
      return ResultUtil.success(id);
    	
    }
    
    
    
    
    
    
    /**
     * 測試集成MyBatis
     * @param name
     * @return
     */
    @GetMapping(value="/user/{name}")
    public Result getUser(@PathVariable("name") String name) throws Exception{
    	
    	return ResultUtil.success(userRepository.getUserByName(name));
    }
    
    

}
